using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

[RequireComponent(typeof(Image))]
public class Joystick : Singleton<Joystick>, IPointerDownHandler, IDragHandler, IPointerUpHandler
{
    [Header("Components")]
    public RectTransform handle;
    
    [Header("Settings")]
    [Range(0, 1)] public float deadZone = 0.2f;
    public float handleRange = 1f;

    private RectTransform baseRect;
    private Canvas canvas;
    private Camera cam;
    
    private Vector2 input = Vector2.zero;
    
    public float Horizontal => input.x;
    public float Vertical => input.y;
    public Vector2 Direction => new Vector2(Horizontal, Vertical);
    public static bool IsMoving = false;
    
    
    private void Start()
    {
        baseRect = GetComponent<RectTransform>();
        canvas = GetComponentInParent<Canvas>();
        cam = canvas.renderMode == RenderMode.ScreenSpaceOverlay ? null : Camera.main;
        handle.anchoredPosition = Vector2.zero;
    }

    public void OnPointerDown(PointerEventData eventData)
    {
        IsMoving = true;    
        OnDrag(eventData);
    }

    public void OnDrag(PointerEventData eventData)
    {
        
        
        // 将屏幕坐标转换为背景Rect的本地坐标
        Vector2 position = RectTransformUtility.WorldToScreenPoint(cam, baseRect.position);
        Vector2 radius = baseRect.sizeDelta / 2;
        // 获取摇杆偏移量
        input = (eventData.position - position) / (radius * canvas.scaleFactor);
        input = new Vector2(input.x, 0);
        // 处理输入范围
        HandleInput(input.magnitude, input.normalized);
        // 移动手柄
        //handle.anchoredPosition = input * radius * handleRange;
        handle.anchoredPosition = new Vector2(input.x * radius.x * handleRange, 0);
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        IsMoving = false;
        
        input = Vector2.zero;
        handle.anchoredPosition = Vector2.zero;
    }

    private void HandleInput(float magnitude, Vector2 normalized)
    {
        // 应用死区
        if (magnitude > deadZone)
        {
            input = normalized * Mathf.Clamp01(magnitude - deadZone) / (1 - deadZone);
        }
        else
        {
            input = Vector2.zero;
        }
    }

    // 获取世界空间方向（可选）
    public Vector3 GetWorldDirection(float yAngle)
    {
        return Quaternion.Euler(0, yAngle, 0) * new Vector3(Horizontal, 0, Vertical);
    }
}